/**
 * Copyright (C) 2011 Audit Logger Project. All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.auditlogger.cli;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.auditlogger.security.SecurityService;

public class LogViewer {
	public static void main (String[] args) {
		validateInputs(args);
		String filePath = args[0];
		try {
			System.out.println("Viewing decrypted log entries in "
					+ filePath + "...");
			System.out.println();
			List<String> records = grepAllSecuredLogEntries(filePath);
			for (String each: records) {
				System.out.println(SecurityService.processSecuredLogMessage(each));
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}

	
	private static List<String> grepAllSecuredLogEntries (String file) throws IOException {
		List<String> securedLogEntries = new ArrayList<String>();
		
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			
			String logRecord = "";
			boolean multiline = false;
			while ((line = reader.readLine()) != null) {
				if (line.contains("START") && line.contains("END")) {
					securedLogEntries.add(line.trim());
				} else if (line.contains("START") && !line.contains("END")) {
					multiline = true;
					logRecord = "";
					logRecord += line.trim();
				} else if (!line.contains("START") && !line.contains("END")) {
					if (multiline) {
						logRecord+= line.trim();
					}
				} else if (!line.contains("START") && line.contains("END")) {
					multiline=false;
					logRecord+=line.trim();
					logRecord = logRecord.substring(logRecord.indexOf("START"), logRecord.length());
					securedLogEntries.add(logRecord);
				}
			}
		}
		catch (Exception ex) {
			ex.printStackTrace(System.err);
		}
		finally {
			if (reader != null) {
				try {reader.close();}catch (Exception ex) {}
			}
		}
		return securedLogEntries;
	}
	
	private static void validateInputs(String[] args) {
		if (args == null || args.length != 1) {
			System.err.println("Usage: LogViewer <filepath>");
			System.exit(-1);
		}
	}

}
